<template>
  <div class="admin-list">
    <div class="header">
      <el-button type="primary" @click="showCreateDialog" v-permission="'sys:admin:create'">
        创建管理员
      </el-button>
    </div>

    <el-table :data="adminList" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column label="角色">
        <template #default="{ row }">
          {{ formatRoleNames(row.roles) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastTime" label="最后登录时间" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" link @click="showEditDialog(row)" v-permission="'sys:admin:update'">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)" v-permission="'sys:admin:delete'"
            :disabled="row.id === 0">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
      @current-change="handlePageChange" />

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" @open="onDialogOpen">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="不修改请留空" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" multiple placeholder="请选择角色" style="width: 100%" clearable>
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.roleName" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/api'

const loading = ref(false)
const adminList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const roleOptions = ref([])

const form = ref({
  username: '',
  password: '',
  realName: '',
  phone: '',
  roles: '',
  roleIds: []
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: false, message: '请输入密码', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }]
}

// 格式化角色名称
const formatRoleNames = (roleIds) => {
  if (!roleIds || !roleOptions.value.length) return '无';

  const roleIdArray = roleIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
  const roleNames = roleIdArray.map(id => {
    const role = roleOptions.value.find(r => r.id === id);
    return role ? role.roleName : '';
  }).filter(name => name);

  return roleNames.length ? roleNames.join(', ') : '无';
}

const fetchData = async () => {
  try {
    loading.value = true
    const res = await adminAPI.getAdminList(currentPage.value - 1, pageSize.value)
    adminList.value = res.data.content
    total.value = res.data.totalElements
  } catch (e) {
    console.error(e)
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await adminAPI.getRoleList(0, 100)
    roleOptions.value = res.data.content
  } catch (e) {
    console.error(e)
    ElMessage.error('获取角色列表失败')
  }
}

const showCreateDialog = () => {
  dialogTitle.value = '创建管理员'
  form.value = {
    username: '',
    password: '',
    realName: '',
    phone: '',
    roles: '',
    roleIds: []
  }
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  dialogTitle.value = '编辑管理员'

  // 处理角色ID数组
  const roleIds = row.roles ?
    row.roles.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id)) :
    [];

  form.value = {
    ...row,
    password: '',
    roleIds
  }

  dialogVisible.value = true
}

// 对话框打开时刷新角色列表
const onDialogOpen = () => {
  fetchRoles();
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate()

  try {
    // 将选择的角色ID转换为字符串格式，适配后端存储
    form.value.roles = form.value.roleIds.join(',')

    if (form.value.id != null) {
      await adminAPI.updateAdmin(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      // 新建管理员时密码为必填
      if (!form.value.password) {
        ElMessage.error('请输入密码')
        return
      }
      await adminAPI.createAdmin(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该管理员吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await adminAPI.deleteAdmin(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error(error.message || '删除失败')
    }
  })
}

const handlePageChange = () => {
  fetchData()
}

onMounted(() => {
  fetchData()
  fetchRoles()
})
</script>

<style scoped>
.admin-list {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>